package com.zyx.crawlerdemo.makrocrawler.db;

import com.zyx.crawlerdemo.makrocrawler.model.ParameterModel;
import com.zyx.crawlerdemo.makrocrawler.model.ProductModel;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;

/**
 * @author Yaxi.Zhang
 * @since 2021/8/12 15:08
 * desc: 数据库工具类
 */
public class MysqlControl {
    /**
     * 根据自己的数据库地址修改
     */
    static DataSource ds = MyDataSource.getDataSource("jdbc:mysql://127.0.0.1:3306/"
    		+ "crawler?useUnicode=true&characterEncoding=UTF8");
    static QueryRunner qr = new QueryRunner(ds);
    public static void executeInsertPro(List<ProductModel> data)  {
        // 数据的维度
        Object[][] params = new Object[data.size()][5];
        for ( int i = 0; i < params.length; i++ ){
            params[i][0] = data.get(i).getId();
            params[i][1] = data.get(i).getName();
            params[i][2] = data.get(i).getPrice();
            params[i][3] = data.get(i).getBrand();
            params[i][4] = data.get(i).getCategory();
        }
        //使用batch方法批量插入
        String sql = "insert into makro_product(id,name,price,brand,category) values (?,?,?,?,?)";
        try {
			qr.batch(sql, params);
			System.out.println("执行数据库完毕！" + "成功插入数据："+data.size() + "条");
		} catch (SQLException e) {
			e.printStackTrace();
		}
    }
    public static void executeInsertPar(List<ParameterModel> data)  {
        // 数据的维度
        Object[][] params = new Object[data.size()][3];
        for ( int i = 0; i < params.length; i++ ){
            params[i][0] = data.get(i).getProductId();
            params[i][1] = data.get(i).getDescription();
            params[i][2] = data.get(i).getModel();
        }
        // 使用batch方法批量插入
        try {
			qr.batch("insert into makro_parameter(product_id,"
					+ "description,model) values (?,?,?)", params);
			System.out.println("执行数据库完毕！" + "成功插入数据："+data.size() + "条");
		} catch (SQLException e) {
			e.printStackTrace();
		}
    }
}